/*

highlight v4

Highlights arbitrary terms.

<http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html>

MIT license.

Johann Burkard
<http://johannburkard.de>
<mailto:jb@eaio.com>

 */

jQuery.fn.highlight = function(c) {
	function e(b, c) {
		var d = 0;
		if (3 == b.nodeType) {
			var a = b.data.toUpperCase().indexOf(c);
			if (0 <= a) {
				d = document.createElement("span");
				d.className = "highlight";
				a = b.splitText(a);
				a.splitText(c.length);
				var f = a.cloneNode(!0);
				d.appendChild(f);
				a.parentNode.replaceChild(d, a);
				d = 1
			}
		} else if (1 == b.nodeType && b.childNodes
				&& !/(script|style)/i.test(b.tagName))
			for (a = 0; a < b.childNodes.length; ++a)
				a += e(b.childNodes[a], c);
		return d
	}
	return this.length && c && c.length ? this.each(function() {
		e(this, c.toUpperCase())
	}) : this
};
jQuery.fn.removeHighlight = function() {
	return this.find("span.highlight").each(function() {
		this.parentNode.firstChild.nodeName;
		with (this.parentNode)
			replaceChild(this.firstChild, this), normalize()
	}).end()
};

// //////////// MAIN
function ajaxSearch() {
	var search = $("#recherche").val();
	var th = $("#rechercheParTheme").prop('checked') ? "on" : "";

	$.post("/AgriotesSVN/RechercherFormation", {
		recherche : search,
		rechercheParTheme : th,
		ajax : "on"
	}).done(function(data) {
		$("#resultat").html(data);
		initTabs();
		highlightSearch();
	});
}

function highlightSearch(){
var term = $('#recherche').val();
if (term.length > 2) {
	$('#resultat').highlight(term);
}}


function initTabs(){
	$('[id^="infoTab"] a').on( "click", function(e) {
		e.preventDefault();
		$(this).tab('show');
	});

}
//

$(document).ready(function() {
	
	// ajax search
	$("#recherche").focus();
	$("#recherche").keyup(function() {
		ajaxSearch();
	});

	$("#rechercheParTheme").change(function() {
		ajaxSearch();
	});

	// tabs
	initTabs();
	// highlight
	highlightSearch();

});
